import React, { useState, useRef,useEffect } from 'react';
import { Calendar, Button, Space, Modal, Form, Input, DatePicker, TimePicker, message } from 'antd';
import type { CalendarProps, ModalProps, FormProps } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');

// 每日预约数据结构
interface BookingDayData {
  remaining: number; // 剩余预约量
  booked: number;    // 已预约数
}

// 预约表单数据类型
interface BookingFormData {
  number: string;
  reservations:number;
  date: Dayjs | null;
  time: Dayjs | null;
  description: string;
}

const BookingCalendar: React.FC = () => {
  // 表单实例

  const [form] = Form.useForm();
  
  // 日历引用
  const calendarRef = useRef<{
    goToday: () => void;
    prev: () => void;
    next: () => void;
  } | null>(null);

  // 状态管理
   const [currentMonth, setCurrentMonth] = useState<Dayjs>(dayjs());
  const [bookingData, setBookingData] = useState<Record<string, BookingDayData>>({
    '2025-10-01': { remaining:200, booked:30 },
    '2025-10-02': { remaining: 300, booked:100 },
    '2025-10-03': { remaining: 400, booked:20 },
    '2025-10-04': { remaining: 3, booked: 2 },
    '2025-10-06': { remaining: 100, booked: 1 },
    '2025-10-07': { remaining: 10, booked: 2 },
    '2025-10-17': { remaining: 100, booked: 100 },
    '2025-10-16': { remaining: 200, booked: 200 },
    '2025-07-13': { remaining: 300, booked: 0 },
    '2025-07-14': { remaining: 400, booked: 0 },
    '2025-07-15': { remaining: 500, booked: 0 },
    '2025-07-20': { remaining: 1000, booked: 0 },
    '2025-07-21': { remaining: 100, booked: 0 },
    '2025-07-22': { remaining: 200, booked: 1 },
    '2025-07-25': { remaining: 10, booked: 1 }
  });
  const [selectedDate, setSelectedDate] = useState<Dayjs | null>(null);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);

  // 处理月份面板变化
  const onPanelChange: CalendarProps['onPanelChange'] = (date) => {
    if (date) {
      setCurrentMonth(date);
    }
  };

  // 处理日期选择
  const onDateSelect: CalendarProps['onSelect'] = (date) => {
    if (date) {
      setSelectedDate(date);
      // 自动填充表单日期
      form.setFieldValue('date', date);
    }
  };

  // 跳转到“今天”
  const handleToday = () => {
    console.log(currentMonth)
    setCurrentMonth(dayjs())
  setSelectedDate(dayjs())
 
  };

  // 打开预约模态框
  const handleAddBooking = () => {
    // 如果有选中日期，使用选中日期；否则使用今天
    const defaultDate = selectedDate || dayjs();
    form.setFieldsValue({
      date: defaultDate,
      time: dayjs().hour(9).minute(0) // 默认上午9点
    });
    setIsModalVisible(true);
  };

  // 提交预约表单
  const handleFormSubmit: FormProps<BookingFormData>['onFinish'] = (values) => {
   console.log(values)

    const dateStr = values.date.format('YYYY-MM-DD');
    const currentData = bookingData[dateStr] || { remaining: 0, booked: 0 };

    // 检查是否还有剩余名额
   

    // 更新预约数据
    setBookingData({
      ...bookingData,
      [dateStr]: {
        ...currentData,
        remaining: values.number,
        booked:values.reservations
      }
    });
  

    message.success('更改成功！');
    setIsModalVisible(false);
    form.resetFields();
  };

    useEffect(() => {
  console.log('bookingData 已更新:', bookingData);
}, [bookingData]); // 仅在 bookingData 变化时触发

  // 自定义日期单元格渲染
  const dateCellRender: CalendarProps['dateCellRender'] = (date) => {
   
     if (!date) return null;
  
  const dateStr = date.format('YYYY-MM-DD');
  // 关键：默认值明确赋值 booked: 0，避免 undefined
  const data = bookingData[dateStr] || { remaining: 0, booked: 0 };
  const isSelected = selectedDate?.isSame(date, 'day');
  const isPast = date.isBefore(dayjs().startOf('day'));
  const isToday = date.isSame(dayjs(), 'day');

  // 修复：处理 total = 0 的情况（避免 NaN 或 100% 异常）
  // const total = data.remaining + data.booked;
  // const bookedPercent = total > 0 ? (data.booked / total) * 100 : 0; // 无数据时 booked 占比 0%
  //  const remainingPercent = 100 - bookedPercent;
  const bookedPercent = data.booked > 0 ? (data.booked/data.remaining)*100 : 0; // 无数据时 booked 占比 0%
   const remainingPercent = data.remaining>0?100:0;
    return (
      <div style={{ 
        padding: '4px', 
        position: 'relative',
        opacity: isPast ? 0.6 : 1,
        backgroundColor: isSelected ? '#f0f7ff' : 'transparent',
        borderRadius: '4px',
       
      }}>
        {/* 日期数字 */}
        <div style={{ 
          marginBottom: '4px', 
          fontWeight: 'bold',
          color: isToday ? '#1890ff' : '#333',
          backgroundColor: isToday ? '#e6f7ff' : 'transparent',
          width: '24px',
          height: '24px',
          borderRadius: '50%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }}>
          {date.date()}
        </div>
        
        {/* 剩余预约量（蓝色条） */}
        <div
          style={{
            backgroundColor: '#e6f7ff',
            color: '#ff18e4ff',
            fontSize: '12px',
            padding: '2px 4px',
            borderRadius: '2px',
            width: '100%',
            height: '20px',
            overflow: 'hidden',
            boxSizing: 'border-box'
          }}
        >
          <div
            style={{
              
              color: '#18ffc1ff',
              width: `${remainingPercent}%`,
              display: 'inline-block',
              height: '100%',
              padding: '0 4px',
              boxSizing: 'border-box',
               // 新增：当宽度为 0 时，仍保留文字（但无背景）
             
            backgroundColor: remainingPercent === 0 ? 'transparent' : '#ff18e4ff',
             whiteSpace: 'nowrap', // 禁止文字换行
            }}
          >
            可约: {data.remaining}
          </div>
        </div>

        {/* 已预约数（红色条） */}
        <div
          style={{
          backgroundColor: '#fff2f0',
          color: '#f5222d',
          fontSize: '12px',
          padding: '2px 4px',
          borderRadius: '2px',
          width: '100%',
          height: '20px',
          overflow: 'hidden',
          marginTop: '2px',
          boxSizing: 'border-box',
          // 新增：即使 bookedPercent=0，也让文字可见（避免宽度 0 导致文字被隐藏）
          display: 'flex',
          alignItems: 'center'
          }}
        >
          <div
            style={{
             
            color: '#f57d22ff',
            width: `${bookedPercent}%`,
            display: 'inline-block',
            height: '100%',
            padding: '0 4px',
            boxSizing: 'border-box',
            // 新增：当宽度为 0 时，仍保留文字（但无背景）
            minWidth: bookedPercent === 0 ? '100%' : 'auto',
            backgroundColor: bookedPercent === 0 ? 'transparent' : '#f5222d',
             whiteSpace: 'nowrap', // 禁止文字换行
             
              
            }}
          >
            已约:<label style={{color:'pink'}}>{data.booked}</label>
          </div>
        </div>

        {/* 约满标记 */}
        { data.remaining===data.booked && data.remaining !=0 && (
          <div style={{
            position: 'absolute',
            top: '4px',
            right: '4px',
            backgroundColor: '#ff4d4f',
            color: 'white',
            fontSize: '10px',
            padding: '1px 4px',
            borderRadius: '2px'
          }}>
            约满
          </div>
        )}
      </div>
    );
  };

  // 模态框配置
  const modalConfig: ModalProps = {
    title: '新增预约',
    open: isModalVisible,
    onCancel: () => setIsModalVisible(false),
    footer: null,
    width: 500
  };

  return (
    <div style={{ maxWidth: '1400', margin: '0 20', padding: '20px' }}>
      {/* 当前月份标题 */}
      <h3 style={{ marginBottom: '16px', textAlign: 'center' }}>
        {currentMonth.format('YYYY年MM月')} 预约日历
      </h3>

      {/* 月份切换与操作按钮 */}
      <Space style={{ marginBottom: '16px', display: 'flex', justifyContent: 'center' }}>
        <Button onClick={handleToday}>今天</Button>
       
        <Button 
          type="primary" 
          style={{ marginLeft: 'auto' }}
          onClick={handleAddBooking}
        >
          新增预约
        </Button>
      </Space>

      {/* 核心日历组件 */}
      <Calendar
         ref={calendarRef}
         selected={selectedDate}
  dateCellRender={dateCellRender} // 内联函数，每次重渲染生成新函数，触发单元格更新
  onPanelChange={onPanelChange}
  onSelect={onDateSelect}
  value={selectedDate || undefined}
  disabledDate={(current) => current && current < dayjs().startOf('day')}
        locale={{
          monthFormat: 'YYYY年MM月',
          today: '今天',
          sunday: '日',
          monday: '一',
          tuesday: '二',
          wednesday: '三',
          thursday: '四',
          friday: '五',
          saturday: '六',
        }}
        style={{
          border: '1px solid #e8e8e8',
          borderRadius: '8px',
          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)'
        }}
      />

      {/* 新增预约模态框 */}
      <Modal {...modalConfig} width={400}>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleFormSubmit}
          initialValues={{
            time: dayjs().hour(9).minute(0)
          }}
        >
            <Form.Item<BookingFormData>
            name="date"
            label="预约日期"
            rules={[{ required: true, message: '请选择预约日期' }]}
          >
            <DatePicker
              disabledDate={(current) => current && current < dayjs().startOf('day')}
              placeholder="选择日期"
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item<BookingFormData>
            name="number"
            label="可预约人数"
            rules={[{ required: true, message: '请输入可预约人数' }]}
          >
            <Input type="number" placeholder="请输入可预约人数" />
          </Form.Item>

          <Form.Item<BookingFormData>
            name="reservations"
            label="已预约人数"
            rules={[{ required: true, message: '请输入已预约人数' }]}
          >
            <Input type="number" placeholder="请输入已预约人数" />
          </Form.Item>


          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
              确认预约
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BookingCalendar;
